package com.zwj.spring_study.a03;

import java.util.ArrayList;
import java.util.List;

/**
 * 模板方法模式
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/5/26 19:38
 */
public class TemplateMethod {
    public static void main(String[] args) {
        MyBeanFactory beanFactory = new MyBeanFactory();
        //开始扩展
        beanFactory.addProcessor(new BeanPostProcessor() {
            @Override
            public void inject() {
                System.out.println("解析@Resource注解，解析@Autowired注解");
            }
        });
        Object bean = beanFactory.getBean();
    }

    static class MyBeanFactory {
        public Object getBean() {
            //不变的部分
            Object bean = new Object();
            System.out.println("构造 " + bean);
            System.out.println("依赖注入 " + bean);
            //可能需要扩展的部分
            for (BeanPostProcessor processor : processors) {
                processor.inject();
            }
            System.out.println("初始化 " + bean);
            return bean;
        }

        private final List<BeanPostProcessor> processors = new ArrayList<>();

        public void addProcessor(BeanPostProcessor beanPostProcessor) {
            processors.add(beanPostProcessor);
        }
    }

    /**
     * 定义抽象的需要扩展的部分
     */
    public interface BeanPostProcessor {
        /**
         * 对依赖注入的扩展
         */
        public void inject();
    }
}
